const DEFAULT_CITY_ID = '101120201';
const API_KEY = '6698455b72b9408396c42145a42079a8';
let currentCityId = DEFAULT_CITY_ID;
// 从URL获取城市ID（用于页面刷新后保留当前城市）
function getCityIdFromUrl() {
    const params = new URLSearchParams(window.location.search);
    return params.get('location'); 
}
// 创建单天天气卡片（将API数据转换为可视化卡片）
function updateUrlWithCityId(cityId, cityName) {
    const url = new URL(window.location.href);
    url.searchParams.set('location', cityId);
    window.history.pushState({}, '', url);
    document.querySelector('#searchInput').value = cityName;
}

function createWeatherCard(dayData) {
    const card = document.createElement('div');
    card.className = 'weather-card';
    const dateEl = document.createElement('div');
    dateEl.className = 'date';
// 1. 添加日期
    dateEl.textContent = dayData.fxDate;
    card.appendChild(dateEl);
    //2.添加图片
    const iconEl = document.createElement('img');
    iconEl.src = `../wearther/icon/${dayData.iconDay}.png`;
    card.appendChild(iconEl);
    //添加文字
    const textEl = document.createElement('div');
    textEl.className = 'text';
    textEl.textContent = dayData.textDay;
    card.appendChild(textEl);
    //添加最高温最低温
    const tempEl = document.createElement('div');
    tempEl.className = 'temp';
    tempEl.textContent = `${dayData.tempMin}℃~${dayData.tempMax}℃`;
    card.appendChild(tempEl);
    //添加风力
    const windEl = document.createElement('div');
    windEl.className = 'wind';
    windEl.textContent = `风力：${dayData.windScaleDay}级 ${dayData.windDirDay}`;
    card.appendChild(windEl);
    const humEl = document.createElement('div');
    //添加湿度
    humEl.className = 'humidity';
    humEl.textContent = `湿度：${dayData.humidity}%`;
    card.appendChild(humEl);

    document.querySelector('.weather-cards').appendChild(card);
}
// 加载7天天气数据并生成卡片
function load7dWeather(cityId) {
    currentCityId = cityId; 
    document.querySelector('.weather-cards').innerHTML = '';
    const xhr = new XMLHttpRequest();
    const apiUrl = `https://pb5ctuk8qx.re.qweatherapi.com/v7/weather/7d?key=${API_KEY}&location=${cityId}`;
    xhr.open('GET', apiUrl, true);
    xhr.send();

    xhr.onreadystatechange = function () {
        if (xhr.readyState !== 4 || xhr.status !== 200) return;
        const res = JSON.parse(xhr.responseText);
        if (res.code === '200') {
            res.daily.forEach(day => createWeatherCard(day));
        }
    };
}

function initSearch() {
    const searchInput = document.querySelector('#searchInput');
    const searchBtn = document.querySelector('.searchBtn');
//点击切换
    searchBtn.onclick = function () {
        const cityName = searchInput.value.trim();
        const xhr = new XMLHttpRequest();
        const geoUrl = `https://pb5ctuk8qx.re.qweatherapi.com/geo/v2/city/lookup?key=${API_KEY}&location=${cityName}`;
        xhr.open('GET', geoUrl, true);
        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4 || xhr.status !== 200) return;
            const res = JSON.parse(xhr.responseText);
            if (res.code === '200' && res.location.length > 0) {
                const cityId = res.location[0].id;//取第一个匹配的城市ID
                const cityName = res.location[0].name; //对应的城市名
                updateUrlWithCityId(cityId, cityName);//更新地址栏
                load7dWeather(cityId);//加载新城市的七天天气
            }
        };
    };
}

function more() {
    const modal = document.getElementById('weatherModal');
    const moreBtn = document.getElementById('moreWeatherBtn');
    const closeBtn = document.getElementById('closeModal');
    let myChart = null;
    //点击更多天气按钮
    moreBtn.addEventListener('click', function () {
        modal.style.display = 'block';
        renderTemperatureChart(currentCityId);
    });

    // 点击关闭按钮 隐藏模态框
    closeBtn.addEventListener('click', function () {
        modal.style.display = 'none';
    });
    //点击模态框背景隐藏模态框
    modal.addEventListener('click', function (e) {
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    });

    function renderTemperatureChart(cityId) {
        const chartDom = document.getElementById('temperatureChart');

        if (myChart) myChart.dispose();
        myChart = echarts.init(chartDom);

       
        const xhr = new XMLHttpRequest();
        const apiUrl = `https://pb5ctuk8qx.re.qweatherapi.com/v7/weather/7d?key=${API_KEY}&location=${cityId}`;
        xhr.open('GET', apiUrl, true);
        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4 || xhr.status !== 200) return;
            const res = JSON.parse(xhr.responseText);
            if (res.code === '200') {
                    // 提取日期最低温最高温
                const dates = res.daily.map(day => day.fxDate);
                const tempMin = res.daily.map(day => parseInt(day.tempMin));
                const tempMax = res.daily.map(day => parseInt(day.tempMax));

                // 图标配置
                const option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: dates,
                        axisLabel: {
                            color: '#333'
                        }
                    },
                    yAxis: {
                        type: 'value',
                        axisLabel: {
                            color: '#333'
                        }
                    },
                    series: [
                        {
                            name: '最低温度',
                            data: tempMin,
                            type: 'line',
                            itemStyle: {
                                color: '#4895ef'
                            },
                            areaStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: 'rgba(72, 149, 239, 0.3)' },
                                    { offset: 1, color: 'rgba(72, 149, 239, 0)' }
                                ])
                            }
                        },
                        {
                            name: '最高温度',
                            data: tempMax,
                            type: 'line',
                            itemStyle: {
                                color: '#6fcf97'
                            },
                            areaStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: 'rgba(111, 207, 151, 0.3)' },
                                    { offset: 1, color: 'rgba(111, 207, 151, 0)' }
                                ])
                            }
                        }
                    ]
                };

                myChart.setOption(option);
            
                window.addEventListener('resize', function () {
                    myChart.resize();
                });
            }
        };
    }
}

document.addEventListener('DOMContentLoaded', function () {
    const urlCityId = getCityIdFromUrl();
    currentCityId = urlCityId || DEFAULT_CITY_ID;
    
    if (urlCityId) {
        const xhr = new XMLHttpRequest();
        const geoUrl = `https://pb5ctuk8qx.re.qweatherapi.com/geo/v2/city/lookup?key=${API_KEY}&location=${urlCityId}`;
        xhr.open('GET', geoUrl, true);
        xhr.send();
        
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const res = JSON.parse(xhr.responseText);
                if (res.code === '200' && res.location.length > 0) {
                    document.querySelector('#searchInput').value = res.location[0].name;
                }
            }
        };
    }
    
    load7dWeather(currentCityId);
    initSearch();
    more(); 
});